import Vue from 'vue';
import Vuex from 'vuex';
import { getLocalStorage, setLocalStorage, removeLocalStorage } from '@/utils/index';
import { removeToken } from '@/utils/auth';

Vue.use(Vuex);

export default new Vuex.Store({
  namespaced: true,
  state: {
    token: getLocalStorage('token'),
    userId: getLocalStorage('userId'),
    userName: getLocalStorage('userName')
  },
  getters: {
    token: state => state.token,
    userId: state => state.userId,
    userName: state => state.userName
  },
  mutations: {
    SET_VALUE_BY_KEY(state, data) {
      for (let key in data) {
        state[key] = data[key];
        setLocalStorage(key, data[key]);
      }
    },
    REMOVE_STATE_BY_KEY(state, key) {
      state[key] = '';
      removeLocalStorage(key);
    }
  },
  actions: {
    Logout({ commit }) {
      console.log('退出登录');
      commit('REMOVE_STATE_BY_KEY', 'token');
      commit('REMOVE_STATE_BY_KEY', 'userId');
      commit('REMOVE_STATE_BY_KEY', 'userName');
      removeToken();
      window.location.reload();
    }
  },
  modules: {}
});
